import express, { Application } from "express";
import bodyParser = require("body-parser");
import bodyParserErrorHandler from "express-body-parser-error-handler";
import type { Request, Response } from "express";
import useRouters from "@routers/index";
import { shedule } from "./shedule/index";
import logger from "./utils/log";
import { JWT } from "./utils/token";
const cors = require('cors')
const CookieParse = require('cookie-parser')

const port: string | number = 3050;

const app: Application = express();
//使用中間件

app.use(express.json());
app.use(bodyParser.json({ limit: "5000mb" }));
app.use(bodyParser.urlencoded({ limit: "5000mb", extended: true }));
app.use(bodyParserErrorHandler());
app.use(cors())
app.use(CookieParse())
//啟動定時任務
shedule.init();


/**
 * @description: 设置允许跨域
 * @param {Request} req
 * @param {Response} res
 * @param {*} next
 * @return {*}
 */
app.all("*", (req: Request, res: Response, next) => {
  //設置請求頭格式，允許跨域
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");
  res.header("Access-Control-Allow-Credentials","true")
  res.header(
    "Access-Control-Allow-Methods",
    "GET, POST ,OPTIONS , PUT, PATCH, DELETE"
  );
  res.header(
    "Access-Control-Allow-Headers",
    "x-access-token, Origin, X-Requested-With, Content-Type, Accept"
  );
  logger.info("調用接口：" + req.url);
  if (req.method.toLocaleLowerCase() === "options") {
    res.status(204).send({});
  }
  //token驗證。未通過認證直接403 --登錄無需驗證，註冊無需驗證
  else if (req.url.split("/")[2] !== "Login" ) {
    if(!JWT.verifytoken(req.headers.authorization))
      res.status(403).send({ code: 403, message: "登錄失效，請重新登錄" });
    else
      next()
  }
  else {
    next();
  }
});

useRouters(app);

//设置404
app.all("*", (_req: Request, res: Response) =>
  res.status(404).send({ code: 404, message: "請求路徑錯誤" })
);

app.listen(port, async () => {
  console.log(`後台已啟動,端口號：${port}`);
});
